--[[
World线程的Copy 列表
--]]

local Lang = require("common.Lang")
local ExcelMap = require("excel.Map")
local CopyConfig = ExcelMap.copy
local SceneConfig = ExcelMap.scene
local Msg = require("core.Msg")
local CopyDefine = require("copy.Define")
local CopyTeamSignW = require("copy.CopyTeamSignW")
local CopyCommon = require("copy.CopyCommon")
local TeamLogic = require("team.TeamLogic")
local Broadcast = require("broadcast.Broadcast")
local FamilyManager = require("family.FamilyManager")
local Config = require("Config")
local MiddleCopySign = require("middle.MiddleCopySign")
local MiddleFamilySign = require("middle.MiddleFamilySign")

copyList = copyList or {}               -- 副本列表 copyList[copyID][room][mapID] = sceneID
mapID2CopyID = mapID2CopyID or {}           -- 地图ID对应副本ID
sceneID2CopyID = sceneID2CopyID or {}         -- 场景ID对应副本ID
sceneID2Room = sceneID2Room or {}           -- 场景ID对应房间号


copyTeam2Copy = copyTeam2Copy or {}         -- teamid->{copyID, roomID}
applyHuman2Copy = applyHuman2Copy or {}     -- uuid -> copyid 

roomDatas = roomDatas or {}               -- 房间数据 roomDatas[copyID][room] {onlineNum=0}
copyHuman2RoomCopy = copyHuman2RoomCopy or {}         -- uuid->{roomID, copyID}

group2Copy = group2Copy or {}   -- 组ID与COPYID

family2Copy = family2Copy or {} -- family uuid -> {copyID, roomID}

-- W里也要初始化副本
function init()
  -- 初始化副本ID对应的地图列表
  if CopyConfig == nil then
        CopyConfig = ExcelMap.copy
  end
  if SceneConfig == nil then
       SceneConfig = ExcelMap.scene
  end
  for copyID,config in pairs(CopyConfig) do
    local roomCount = SceneConfig[config.mapList[1]].scene_count 
    local logicid   = SceneConfig[config.mapList[1]].logic_id
    for _,mapID in ipairs(config.mapList) do
      assert(not mapID2CopyID[mapID], mapID)
      mapID2CopyID[mapID] = copyID
      if roomCount ~= SceneConfig[mapID].scene_count then
        assert(nil, "W copy init error, mapID:" .. mapID .. " scenecount error")
      end
      if logicid ~= SceneConfig[mapID].logic_id then
        assert(nil, "W maplist not in same logic: mapid:".. mapID.. " copyID="..copyID)
      end 
    end
    group2Copy[config.group] = group2Copy[config.group] or {}
    group2Copy[config.group][#group2Copy[config.group] + 1] = copyID
  end 
end

function getCopyLogicID(copyID)
  local config = CopyConfig[copyID]
  return SceneConfig[config.mapList[1]].logic_id
end

function isCopy(mapID)
  return mapID2CopyID[mapID]
end
-- 断线操作
function onLogout(human)
  applyHuman2Copy[human._id] = nil
  CopyTeamSignW.onLogout(human)
end

function clearTeamCopy(copyID, roomID)
  for k, v in pairs(copyTeam2Copy) do
      if v.copyID == copyID and v.roomID == roomID then
          copyTeam2Copy[k] = nil
      end  
  end
end

function clearFamilyCopy(copyID, roomID, add)
   for k,v in pairs(family2Copy) do
          local flag
          for kk,vv in pairs(v) do
              if kk == copyID and vv.roomID == roomID then
                  v[kk] = nil
                  flag = true
                  local family = FamilyManager.findByUuid(k)
                  if family and add then
                      FamilyManager.addCopyTimes(family)                      
                  end                  
                  break
              end
          end
          if flag then
              break
          end
    end
end


--申请副本房间
function applyCopyRoom(human, copyID, startTime)
   local copyConfig = CopyConfig[copyID]
   if not copyConfig then
      return
   end
   if applyHuman2Copy[human._id] then
      return
   end   
   if copyConfig.type == CopyDefine.COPY_TYPE_TEAM then  
    if Config.IS_MIDDLE then
        return MiddleCopySign.middleTeamCopyRoom(human, copyID)
    end
    local team = TeamLogic.getTeamByUuid(human._id) 
    -- 进入组队副本要有队伍 所以这里创建一个人的队伍
    if team == nil then 
      TeamLogic.create(human)
      TeamLogic.sendList(human)  
      team = TeamLogic.getTeamByUuid(human._id)   
    end   
    local info = copyTeam2Copy[team.id]
    if info then
        if info.copyID == copyID then --队员
            if os.time() - info.startTime > 30 then
                Broadcast.sendBroadcast(human, Lang.MOUSE+Lang.TEAM, Lang.COPY_ENTER_ERR_TEAM_TIME_OUT)
                return                
            end
            if roomDatas[info.copyID] and roomDatas[info.copyID][info.roomID] and roomDatas[info.copyID][info.roomID].quitList[human._id] then
                Broadcast.sendBroadcast(human, Lang.MOUSE+Lang.TEAM, Lang.COPY_ENTER_ERR_NO_TEAMLEADER)
                return
            end
            local msg = Msg.wl.WL_CROSS_ROOM_APPLY_RESULT
            msg.copyid = copyID
            msg.roomid = info.roomID
            Msg.send2logic(msg, human._id)            
            return
        end
        return -- 这里直接扔掉。
    end
    local leaderUuid = TeamLogic.getLeaderUuid(team)
    if leaderUuid ~= human._id then -- 只有队长才能申请
        Broadcast.sendBroadcast(human, Lang.MOUSE+Lang.TEAM, Lang.COPY_ENTER_ERR_NO_TEAMLEADER)
        return
    end
  elseif copyConfig.type == CopyDefine.COPY_TYPE_FAMILY then -- 军团副本
    local family = FamilyManager.findByUuid(human.familyUuid)
    if not family then
        Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.FAMILY_NOT_EXIST)
        return
    end
    if family.familyCopyTimes >=2 then
        Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.FAMILY_COPY_HAD_FINISH)
        return
    end
    if not family2Copy[family._id] then 
        Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.FAMILY_COPY_NOT_START)
        return
    end
    for copy,v in pairs(family2Copy[family._id]) do
      if (copy == copyID or CopyCommon.isSameGroupCopy(copy, copyID)) and v.roomID then
          copyID = copy
          applyHuman2Copy[human._id] = copyID
          finishApplyCopyRoom(human._id, human, copyID, v.roomID, true)
          return
      end
    end
    Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.FAMILY_COPY_NOT_START)
    return
  elseif copyID == CopyDefine.COPY_FAMILYWAR_ID then
        if Config.IS_MIDDLE then
            MiddleFamilySign.applyHumanRoom(human)
            return
        end
  end
  sendApplyRoom(human._id, copyID, startTime)
end

--跨服申请副本房间
function applyCopyRoomM(uuid, copyID, startTime)
  local copyConfig = CopyConfig[copyID]
  if not copyConfig or copyConfig.type ~= CopyDefine.COPY_TYPE_TEAM then
      return
  end
  if applyHuman2Copy[uuid] then
      return
  end   
  sendApplyRoom(uuid, copyID, startTime)
end



function sendApplyRoom(uuid, copyID, startTime)
  applyHuman2Copy[uuid] = copyID
  local msg = Msg.wl.WL_CROSS_ROOM_APPLY
  msg.copyid = copyID
  msg.startTime = startTime or 0
  msg.uuid = uuid
  Msg.send2logic_id(msg, getCopyLogicID(copyID))
end

--完成申请
function finishApplyCopyRoom(uuid, human, copyID, roomID, direct)
  local copyConfig = CopyConfig[copyID]
  if not copyConfig then
      return
  end
  if applyHuman2Copy[uuid] == nil then
      return
  end
  applyHuman2Copy[uuid] = nil
  if copyConfig.type == CopyDefine.COPY_TYPE_TEAM then  
      if Config.IS_MIDDLE then
          MiddleCopySign.finishApplyCopyRoomM(uuid, copyID, roomID)
          return
      end
      if CopyTeamSignW.finishApplyCopyRoom(uuid, copyID, roomID) then
            local info = {}
            info.copyID = copyID
            info.roomID = roomID
            info.startTime = os.time()
            local team = TeamLogic.getTeamByUuid(human._id)
            roomDatas[info.copyID][info.roomID].teamID = team.id
            copyTeam2Copy[team.id] = info      
            return  --匹配进入
      end
      local team = TeamLogic.getTeamByUuid(human._id)
      if team == nil then
          return
      end
      local info = copyTeam2Copy[team.id]
      if info then
          return
      end
      if roomID ~= 0 then
          info = {}
          info.copyID = copyID
          info.roomID = roomID
          info.startTime = os.time()
          roomDatas[info.copyID][info.roomID].teamID = team.id
          copyTeam2Copy[team.id] = info
          local msg = Msg.gc.GC_COPY_TEAM_NOTIFY_ENTER
          msg.copyID = copyID
          msg.difficult = copyConfig.difficult
          msg.copyName = copyConfig.name  
          Msg.sendMulti(msg, TeamLogic.getTeamOnlineMemberFD(team, human._id))
       end
  elseif copyConfig.type == CopyDefine.COPY_TYPE_FAMILY then
       if not direct and roomID ~= 0 then
          local family = FamilyManager.findByUuid(human.familyUuid)
          if not family then
            return
          end
          if not family2Copy[family._id] or not family2Copy[family._id][copyID] then
            return
          end
          local err = CopyCommon.checkEnterCondition(human, copyID)
          if err then
             family2Copy[family._id][copyID] = nil
             Broadcast.sendBroadcast(human, Lang.MOUSE, err)
             return
          end
          if family2Copy[family._id][copyID].roomID then -- error
            return
          end          
          family2Copy[family._id][copyID].roomID = roomID
          roomDatas[copyID][roomID].familyUuid = family._id
          local msg = Msg.gc.GC_FAMILY_ACT_COPY_START
          msg.copyID = copyID
          FamilyManager.sendFamily(msg, family)      
          msg = Msg.gc.GC_BROADCAST
          msg.type = Lang.FAMILY
          if CopyDefine.COPY_FAMILY_COPY_ID[1] == copyID then
            msg.msg = string.format(Lang.FAMILY_COPY_BROADCAST, copyID)
          else
            msg.msg = string.format(Lang.FAMILY_COPY_BROADCAST2, copyID)
          end
          FamilyManager.sendFamily(msg, family)  
          Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.FAMILY_COPY_HAD_START)
       elseif roomID == 0 then
          local family = FamilyManager.findByUuid(human.familyUuid)
          if not family then
            return
          end          
          if not family2Copy[family._id] then
            return
          end
          family2Copy[family._id][copyID]  = nil
       end
  elseif copyID == CopyDefine.COPY_FAMILYWAR_ID then
        if Config.IS_MIDDLE then
            MiddleFamilySign.finishApplyRoom(uuid, roomID)
            return         
        end
  end 
  local msg = Msg.wl.WL_CROSS_ROOM_APPLY_RESULT
  msg.copyid = copyID
  msg.roomid = roomID
  msg.uuid = human._id
  Msg.send2logic(msg, human._id)
end
